package 岛屿数量;

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     * <p>
     * 判断岛屿数量
     *
     * @param grid char字符型二维数组
     * @return int整型
     */
    static int N = 210, n, m;
    static boolean[][] st = new boolean[N][N];
    static int[] dx = {-1, 1, 0, 0};
    static int[] dy = {0, 0, -1, 1};

    public int solve(char[][] grid) {
        n = grid.length;
        m = grid[0].length;
        int ret = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == '1' && !st[i][j]) {
                    bfs(grid, new PII(i, j));
                    ret++;
                }
            }
        }

        return ret;
    }

    private void bfs(char[][] grid, PII start) {
        st[start.x][start.y] = true;
        Queue<PII> q = new LinkedList<>();
        q.offer(start);
        while (!q.isEmpty()) {
            PII t = q.poll();
            for (int i = 0; i < 4; i++) {
                int a = t.x + dx[i], b = t.y + dy[i];
                if (a < 0 || a >= n || b < 0 || b >= m) {
                    continue;
                }
                if (grid[a][b] != '1') {
                    continue;
                }
                if (st[a][b]) {
                    continue;
                }
                st[a][b] = true;
                q.offer(new PII(a, b));
            }
        }
    }
}

class PII {
    int x, y;

    public PII(int x, int y) {
        this.x = x;
        this.y = y;
    }
}